package org.thukari.controller;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import org.thukari.GetStarted;
import org.thukari.entity.CountData;
import org.thukari.entity.DealData;
import org.thukari.entity.DemoData;
import org.thukari.service.WriteOutService;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DemoDataListener implements ReadListener<DemoData> {
    private static final WriteOutService writeOutService = new WriteOutService();

    private static final int BATCH_COUNT = 100;  //一次性最多将多少行存入内存中

    private List<DemoData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private Map<String, CountData> dataMap = new HashMap<>();

    private Map<String, String> dealedMap = new HashMap<>();

    private Map<String, DealData> concreteMap = new HashMap<>();

    private Map<String, CountData> memberDataMap = new HashMap<>();

    private int count = 0;

    private List<String> deallistNumList = new ArrayList<>();

    private List<String> listNumList = new ArrayList<>();

    private static final String REGEX1 = ".*其它+.*";

    private static final String REGEX2 = ".*其他+.*";

    private static final String REGEX3 = ".*问题单+.*";

    private static final String REGEX4 = ".*商企ICT.*";

    private static final String REGEX5 = ".*规则1+.*";

    @Override
    public void invoke(DemoData demoData, AnalysisContext analysisContext) {
        cachedDataList.add(demoData);
        if (cachedDataList.size() >= BATCH_COUNT) {
            dataProcess(cachedDataList);
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        dataProcess(cachedDataList);
        count++;
        System.out.println(dataMap.toString());
        if (count == 2) {
//            getSeparateDeal(concreteMap);
            writeOutService.writeOut(dataMap, concreteMap, memberDataMap);
        }
    }

    private void getSeparateDeal(Map<String, DealData> concreteMap) {
        String regex = "区分公司";
        Pattern pattern = Pattern.compile(regex);
        for (Map.Entry<String, DealData> entry : concreteMap.entrySet()) {
            if (entry.getValue().getDistrict() == null) {
                if (entry.getValue().getReceiveDistrict() != null) {
                    Matcher matcher = pattern.matcher(entry.getValue().getReceiveDistrict());
                    String district = matcher.replaceFirst("");
                    if (dataMap.get(district) != null) {
                        dataMap.get(district).getDataMap().get("成交").stockUp();
                    }
                } else {
                    dataMap.get("其它").getDataMap().get("成交").stockUp();
                }
            }
        }
    }

    private void dataProcess(List<DemoData> demoDataList) {
        if (count == 0) {
            for (DemoData demoData : demoDataList) {
                if (demoData.getDealSerial() != null) {
                    dealedMap.putIfAbsent(demoData.getDealSerial(), "");
                }
            }
            recordDeal(demoDataList);
        } else if (count == 1) {
            getOrderSent(demoDataList);
            getDeal(demoDataList);
        }
    }

    private void getDeal(List<DemoData> demoDataList) {
        for (DemoData demoData : demoDataList) {
            if (concreteMap.get(demoData.getSerial()) != null) {
                DealData dealData = concreteMap.get(demoData.getSerial());
                dealData.setCountDate(demoData.getOrderDate());
                dealData.setSerialNum(demoData.getSerial());
                dealData.setMember(demoData.getMember());
                dealData.setDistrict(demoData.getDistrict());
                dealData.setBusinessType(demoData.getBusinessType());
                dealData.setType01(demoData.getType01());
                dealData.setType02(demoData.getType02());
                if (demoData.getNote() != null && Pattern.matches(REGEX4, demoData.getNote())) {
                    dealData.setNote(demoData.getNote());
                }
                if (demoData.getSource()!=null && Pattern.matches(REGEX4,demoData.getSource())){
                    dealData.setNote(demoData.getSource());
                }
            }
        }
    }

    private void recordDeal(List<DemoData> demoDataList) {
        for (DemoData demoData : demoDataList) {
            if (concreteMap.get(demoData.getDealSerial()) == null) {
                DealData dealData = new DealData();
                dealData.setCountDate(demoData.getOrderDate());
                dealData.setSerialNum(demoData.getDealSerial());
                dealData.setOrderDate(demoData.getOrderDate());
                dealData.setOrder(demoData.getOrder());
                dealData.setOrderNum(demoData.getOrderNum());
                dealData.setServiceProvided(demoData.getServiceProvided());
                dealData.setProductType(demoData.getProductType());
                dealData.setReceiveDate(demoData.getReceiveDate());
                dealData.setStatusDate(demoData.getStatusDate());
                dealData.setOrderStatus(demoData.getOrderStatus());
                dealData.setCustomerName(demoData.getCustomerName());
                dealData.setPhoneNum(demoData.getPhoneNum());
                dealData.setAddressID(demoData.getAddressID());
                dealData.setReceiveDistrict(demoData.getReceiveDistrict());
                dealData.setGridID(demoData.getGridID());
                dealData.setGridName(demoData.getGridName());
                dealData.setReceiveStore(demoData.getReceiveStore());
                dealData.setManagerY(demoData.getManagerY());
                dealData.setManager(demoData.getManager());
                dealData.setManagerDomain(demoData.getManagerDomain());
                dealData.setSecManagerY(demoData.getSecManagerY());
                dealData.setSecManager(demoData.getSecManager());
                dealData.setSecManagerDomain(demoData.getSecManagerDomain());
                dealData.setRule(demoData.getRule());
                concreteMap.put(demoData.getDealSerial(), dealData);
            } else {
                if (concreteMap.get(demoData.getDealSerial()).getReceiveDistrict() == null && demoData.getReceiveDistrict() != null) {
                    concreteMap.get(demoData.getDealSerial()).setReceiveDistrict(demoData.getReceiveDistrict());
                }
            }
        }
    }

    private void getOrderSent(List<DemoData> demoDataList) {
        for (DemoData demoData : demoDataList) {
            if (demoData.getSerial() == null) {
                continue;
            }
            if (demoData.getDistrict() != null && !Pattern.matches(REGEX3, demoData.getDistrict())) {
                if (Pattern.matches(REGEX1, demoData.getDistrict())) {
                    demoData.setDistrict("其它");
                }
                if (Pattern.matches(REGEX2, demoData.getDistrict())) {
                    demoData.setDistrict("其它");
                }
                if (dataMap.get(demoData.getDistrict()) == null) {
                    dataMap.put(demoData.getDistrict(), new CountData(demoData.getDistrict(), 0, 0, 0));
                    initDataMap(demoData.getDistrict(), dataMap);
                }
                Map<String, CountData> districtMap = dataMap.get(demoData.getDistrict()).getDataMap();
                LocalDate yesterday = LocalDate.now().minusDays(1);
                Instant instant = yesterday.atStartOfDay().atZone(ZoneId.of("Asia/Shanghai")).toInstant();
                if (demoData.getDate().compareTo(Date.from(instant)) == 0) {
                    if (demoData.getBusinessType().equals("存量")) {
                        districtMap.get("当日").stockUp();
                    } else {
                        if (demoData.getType01().equals("宽带") || demoData.getType01().equals("专线")) {
                            districtMap.get("当日").fiberUp();
                        } else {
                            districtMap.get("当日").otherUp();
                        }
                    }
                }
                if (demoData.getDate().getMonth() == GetStarted.standardDate) {
                    if (demoData.getBusinessType().equals("存量")) {
                        districtMap.get("当月").stockUp();
                    } else {
                        if (demoData.getType01().equals("宽带") || demoData.getType01().equals("专线")) {
                            districtMap.get("当月").fiberUp();
                        } else {
                            districtMap.get("当月").otherUp();
                        }
                    }
                }

//                LocalDate localDate = LocalDate.of(2025, 2, 7);


                if (concreteMap.get(demoData.getSerial()) != null) {
//                    if (demoData.getNote()!=null&&Pattern.matches(REGEX4,demoData.getNote())&&concreteMap.get(demoData.getSerial()).getStatusDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().isAfter(localDate)) {
//                        continue;
//                    }
                    if (demoData.getNote() != null && concreteMap.get(demoData.getSerial()).getRule() != null && Pattern.matches(REGEX4, demoData.getNote()) && !Pattern.matches(REGEX5, concreteMap.get(demoData.getSerial()).getRule())) {
                        continue;
                    }
                    if (demoData.getBusinessType().equals("存量")) {
                        districtMap.get("成交").stockUp();
                    } else {
                        if (demoData.getType01().equals("宽带") || demoData.getType01().equals("专线")) {
                            districtMap.get("成交").fiberUp();
                        } else {
                            districtMap.get("成交").otherUp();
                        }
                    }
                }

            }

            if (demoData.getNote() != null && Pattern.matches(REGEX4, demoData.getNote())) {
                continue;
            }

            if (demoData.getMember() != null) {
                if (memberDataMap.get(demoData.getMember()) == null) {
                    memberDataMap.put(demoData.getMember(), new CountData(demoData.getMember(), 0, 0, 0));
                    initDataMap(demoData.getMember(), memberDataMap);
                }


                LocalDate yesterday = LocalDate.now().minusDays(1);
                Instant instant = yesterday.atStartOfDay().atZone(ZoneId.of("Asia/Shanghai")).toInstant();
                if (demoData.getDate().compareTo(Date.from(instant)) == 0) {
                    if (!Pattern.matches(REGEX3, demoData.getDistrict())) {
                        memberDataMap.get(demoData.getMember()).getDataMap().get("当日").otherUp();
                    } else {
                        memberDataMap.get(demoData.getMember()).getDataMap().get("当日").fiberUp();
                    }
                }
                if (demoData.getDate().getMonth() == GetStarted.standardDate) {
                    if (!Pattern.matches(REGEX3, demoData.getDistrict())) {
                        memberDataMap.get(demoData.getMember()).getDataMap().get("当月").otherUp();
                    } else {
                        memberDataMap.get(demoData.getMember()).getDataMap().get("当月").fiberUp();
                    }
                }
                if (dealedMap.get(demoData.getSerial()) != null) {
                    memberDataMap.get(demoData.getMember()).stockUp();
                }

            }
        }
    }

    private void initDataMap(String districtName, Map<String, CountData> dataMap) {
        Map<String, CountData> dataMap1 = new HashMap<>();
        dataMap1.put("当日", new CountData("当日", 0, 0, 0));
        dataMap1.put("当月", new CountData("当月", 0, 0, 0));
        dataMap1.put("成交", new CountData("成交", 0, 0, 0));
        dataMap.get(districtName).setDataMap(dataMap1);
    }
}
